package com.software.graduationproject.modules.user.service;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Strings;
import com.software.graduationproject.commons.exception.ServiceException;
import com.software.graduationproject.commons.util.JwtUtil;
import com.software.graduationproject.commons.util.SMSUtils;
import com.software.graduationproject.modules.marketers.service.MarketersService;
import com.software.graduationproject.modules.sys.mapper.SysMenuMapper;
import com.software.graduationproject.modules.user.entity.User;
import com.software.graduationproject.modules.user.mapper.UserMapper;

import com.software.graduationproject.commons.redis.RedisCache;
import com.software.graduationproject.modules.user.object.UserUpdateQo;
import com.software.graduationproject.modules.user.object.UserVo;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * UserService : 
 * ---------------------------------------------------------------------------------------------------------------------
 */
@Service
public class UserService  {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MarketersService marketersService;


    /**
     * 用户输入手机号
     * 生成一个随机的四位数验证码
     * 并通过第三方平台发送到手机
     * @param phone
     * @return
     */
    public boolean sendSms(String phone) {
        this.selectByPhone(phone);
        String code = RandomStringUtils.randomNumeric(4);
        redisCache.setCacheObject(phone,code,5,TimeUnit.MINUTES);
        boolean sendMessage = SMSUtils.sendMessage(phone, code);
        return sendMessage;
    }


    public void createQo(User user){
        userMapper.insert(user);
    }

    public void updateQo(UserUpdateQo qo){
        User user = userMapper.selectById(qo.getId());
        if (user == null){
            throw  new ServiceException("数据不存在");
        }
        BeanUtil.copyProperties(qo,user);
        String picUrl = qo.getPicUrl();
        if (!Strings.isNullOrEmpty(picUrl)) {
            // 解码Base64字符串为字节数组
            byte[] decodedBytes = Base64.getDecoder().decode(picUrl);
            // 创建 MockMultipartFile 对象
            MultipartFile file = new MockMultipartFile("img.jpg", decodedBytes);
            String upload = marketersService.upload(file);
            user.setPicUrl(upload);
        }
        userMapper.updateById(user);
    }

    public UserVo selectVo(Long id) {
        UserVo userVo = new UserVo();
        User user = userMapper.selectById(id);
        BeanUtil.copyProperties(user,userVo);
        return userVo;
    }

    public UserVo login(String phone, String code) {
        if (verifyCode(phone, code)) {
            String jwt = JwtUtil.createJWT(phone);
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("mobile", phone);
            User user = userMapper.selectOne(wrapper);
            UserVo userVo = new UserVo();
            if (user == null) {
                User newUser = new User();
                newUser.setNickname("用户"+phone);
                newUser.setMobile(phone);
                userMapper.insert(newUser);
                BeanUtil.copyProperties(newUser,userVo);
                userVo.setToken(jwt);
                return userVo;
            }
            BeanUtil.copyProperties(user,userVo);
            userVo.setToken(jwt);
            return userVo;
        }
        return null;
    }

    public boolean verifyCode(String phone, String code) {
        String savedCode = redisCache.getCacheObject(phone);
        if (savedCode != null && savedCode.equals(code)) {
            // 验证码验证成功，从缓存中删除验证码
            redisCache.deleteObject(phone);
            return true;
        } else {
            return false;//验证失败
        }
    }

    public void selectByPhone(String phone) {
        if (!Strings.isNullOrEmpty(phone)) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getMobile,phone);
            User user = userMapper.selectOne(queryWrapper);
            if (user != null) {
                throw new ServiceException("该手机号已被注册");
            }
        }
    }
}
